package com.sky.service.user.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.mapper.admin.MerchantMapper;
import com.sky.mapper.user.AddressBookMapper;
import com.sky.mapper.user.OrderDetailMapper;
import com.sky.mapper.user.OrderMapper;
import com.sky.mapper.user.ShoppingCartMapper;
import com.sky.pojo.*;
import com.sky.result.Result;
import com.sky.service.user.OrderService;
import com.sky.utils.MapUtils;
import com.sky.vo.OrderSubmitVO;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;


    /**
     * 得出预计送达时间
     *
     * @param shopId
     * @param customerAddress
     * @return
     */
    @Override
    public Result getEstimateDeliveryTime(Long shopId, String customerAddress) {
        //首先我们得出来当前用户购物车里面的菜品或者套餐,然后算出来总时间
        Long id = BaseContext.getCurrentId();
        Integer total = shoppingCartMapper.selectTotalMakeTimeByUserId(id);
        //计算配送时间
        Merchant merchant = merchantMapper.selectById(shopId);
        //秒
        Integer costTime = MapUtils.baoiduTwoPointCostTime(merchant.getShopAddress(), customerAddress);
        LocalDateTime deliveryTime = LocalDateTime.now().plusSeconds(total * 60 + costTime + 600);
        return Result.success(deliveryTime.toString());

    }

    /**
     * 下单
     *
     * @param dto
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO dto) {
        // TODO 创建orders
        Orders orders=new Orders();
        //我们的Order表字段里面有点多,先属性拷贝
        BeanUtil.copyProperties(dto,orders);
        //然后手动赋值当前用户的id,订单号,订单状态,下单时间,支付状态!还有个结账时间支付的时候才会有
        //点击去支付的时候就创建订单,因为有人可能取消支付了,所以我们在点支付的时候就去设置订单状态和支付状态
        //是待付款和未支付
        orders.setUserId(BaseContext.getCurrentId());
        orders.setNumber(UUID.randomUUID().toString().replace("-",""));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        //查询地址簿信息
        AddressBook addressBook = addressBookMapper.getById(dto.getAddressBookId());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getProvinceName()+addressBook.getCityName()+addressBook.getDistrictName());
        orders.setConsignee(addressBook.getConsignee());
        //从之前购物车的接口里面拿总时间
        Integer totalMakeTime = shoppingCartMapper.selectTotalMakeTimeByUserId(BaseContext.getCurrentId());
         orders.setMealTime(LocalDateTime.now().plusMinutes(totalMakeTime));
         //保存订单
        orderMapper.save(orders);
        //然后下面保存订单详情的信息
        //根据Id从购物车里面拿东西
        //创建订单详情的集合
        List<OrderDetail> orderDetailList=new ArrayList<>();
        ShoppingCart shoppingCart=new ShoppingCart();
        shoppingCart.setUserId(BaseContext.getCurrentId());
        List<ShoppingCart> shoppingCarts = shoppingCartMapper.selectByCondition(shoppingCart);
        //遍历购物车集合然后把每一个都加到订单详情里面
        shoppingCarts.forEach(shoppingCart1 -> {
            OrderDetail orderDetail=new OrderDetail();

            BeanUtil.copyProperties(shoppingCart1,orderDetail);
            //只需要自己加一个订单单号,其他都是拷贝
            orderDetail.setOrderId(orders.getId());
            orderDetailList.add(orderDetail);
        });
        //保存订单详情
        orderDetailMapper.saveBatch(orderDetailList);
        //然后清空购物车
        shoppingCartMapper.deleteByUserId(BaseContext.getCurrentId());
        //构建返回
        OrderSubmitVO orderSubmitVO=OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;



    }
}
